import React from 'react'
import ReactDOM from 'react-dom'
import fetch from 'isomorphic-fetch'
import { SearchOutlined } from '@ant-design/icons';
import { Input, Menu, Dropdown, Icon, List, Avatar, Button, Carousel, Select, notification, Modal } from 'antd';

import { openNotification_util } from './shipSRM/util/util.js';

import bgcenter from './../img/newsucai/index-center.png'

import userpic from './../img/newsucai/userpic.png'
import passwordpic from './../img/newsucai/passwordpic.png'
import Resetpassword from './resetpassword.js';
import Registaccount from './registaccount.js'


var storage = window.localStorage;

const { Option } = Select;
class Login extends React.Component {
  constructor(props) {
    super(props)

  }

  state = {
    sfz: "",
    openid: "",
    corplistdata: [],
    corpid: "",
    formdata: { username: "", password: "" },
    deviceno: "",
    ddLoginVisible: false,
    ddLoginUrl: ""
  }


// JWT令牌管理
setToken = (token) => {
  storage.token = token;
  // 设置令牌过期时间（4小时后）
  storage.tokenExpireTime = Date.now() + 4 * 60 * 60 * 1000;
}




  handlepassword = () => {
    if (event && event.target && event.target.value) {
      let value = event.target.value;
      // alert(value)
      this.setState(() => ({ password: value }))
    }

  }


  handlechange_normal = (key, e) => {
    //this.openNotification(e.target.value)
    let data = Object.assign({}, this.state.formdata, { [key]: e.target.value });
    this.setState({ formdata: data })
  };

  checkdatavalid = (...args) => {
    for (let item of args) {    //for of 推荐用在遍历数组
      var checkvalue = this.state.formdata[item]
      if (checkvalue == "" || checkvalue == null || checkvalue == undefined)
        return false;
    }
    return true;
  };




  //这个日期字符串获取更好用，根据需求返回三种1：年月日 2年月日时分秒 31970开始时间秒数用作id
  getCurrentDate = (format) => {
    var now = new Date();
    var year = now.getFullYear(); //得到年份
    var month = now.getMonth();//得到月份
    var date = now.getDate();//得到日期
    var day = now.getDay();//得到周几
    var hour = now.getHours();//得到小时
    var minu = now.getMinutes();//得到分钟
    var sec = now.getSeconds();//得到秒
    month = month + 1;
    if (month < 10) month = "0" + month;
    if (date < 10) date = "0" + date;
    if (hour < 10) hour = "0" + hour;
    if (minu < 10) minu = "0" + minu;
    if (sec < 10) sec = "0" + sec;
    var time = "";
    //精确到天
    if (format == 1) {
      time = year + "-" + month + "-" + date;
    }
    //精确到分
    else if (format == 2) {
      time = year + "-" + month + "-" + date + " " + hour + ":" + minu + ":" + sec;
    }
    else if (format == 3) {
      time = now.getTime();
    }
    else if (format == 4) {
      time = year + "--" + month + "--" + date;
    }

    return time;
  }

  //通用提醒
  openNotification = (text) => { notification.open({ message: '提示', description: text, onClick: () => { }, }); };




  handlelogin = () => {

    if (!this.checkdatavalid("username", "password")) {
      this.openNotification("检查表格是否为空")
      return false;
    }

    var ddd = this.state;
    var logintime = this.getCurrentDate(2)

    fetch("/admin/sys/login", {
      method: 'POST',
      mode: 'cors',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ "data": this.state.formdata })
    }
    ).then(response => {
      return response.json();
    }).then(data => {
      // 检查返回的数据结构
      if (data.rtstatus === false) {
        // 处理登录失败的情况
        this.openNotification(data.rtmessage || "登录失败")
        return;
      }

      // console.log("================login返回的data===============",data);
      
      // 兼容旧版返回格式和新版返回格式
      let userData;
      let token;
      
      if (data.rtstatus === true && data.resultdata) {

       
        // 新版本格式：{ success: true, data: { recordsets: [...], token: ... } }
        if (data.resultdata && data.resultdata[0] && data.resultdata.length > 0) {
          userData = data.resultdata[0];
          token = userData.token;
        }
      } else if (data.rowlength !== undefined) {
        // 旧版本格式：{ rowlength: 1, recordsets: [...] }
        if (data.rowlength == 0) {
          this.openNotification("验证不通过，登录失败")
          return;
        }
        userData = data.recordsets[0][0];
        token = userData.token;
      }

      if (!userData) {
        this.openNotification("登录数据格式错误")
        return;
      }

      // 存储用户基本信息
      storage.ygxm = userData.xm;
      storage.js = userData.js;
      storage.zh = userData.zh;
      storage.ygbh = userData.zh;
      storage.userid = userData.id;
      storage.yhlx = userData.yhlx;
      storage.gysbm = userData.zh;
      storage.logintime = logintime;

      // 存储JWT令牌
      if (token) {
        storage.token = token;
        // 设置令牌过期时间（4小时后）
        storage.tokenExpireTime = Date.now() + 4 * 60 * 60 * 1000;
        console.log('JWT令牌已存储:', token.substring(0, 20) + '...');
        
      } else {
        console.warn('未收到JWT令牌');
      }

      this.openNotification(`欢迎您，${userData.xm}!`)
      this.props.history.push({ pathname: '/shipSRM/mainpage', state: {} });

    }).catch(error => {
      console.error('登录请求失败:', error);
      this.openNotification("网络连接失败，请稍后重试");
    });
  }


  querycorplist = () => {
    fetch("/admin/customlist/getcorplist", {
      method: 'POST',
      mode: 'cors',
      // credentials: 'include',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ "data": this.state })
    }
    ).then(response => {

      return response.json();
    }).then(data => {
      this.setState({
        corplistdata: data.rows
      });

    });


  }


  handlechangeSelect_normal_cx = (key, value, option) => {

    storage.logincx = value;

  };


  handlechangeSelect_normal_bb = (key, value, option) => {

    storage.loginbb = value;

  };


  handleKeyDown = (e) => {
    if (e.keyCode === 13) {
      this.handlelogin()
    }
  }

  componentDidMount() {
    document.addEventListener('keydown', this.handleKeyDown);

    storage.loginbb = "A班";
    storage.logincx = "1#线";

    // 检查URL中是否有钉钉登录的code或error参数
    console.log(window.location.href);
    //获取window.location.href的code  http://localhost:2233/#/?code=60c64aa824543a30bdab93fc9f6ba53c&state=STATE
    //没有code参数，说明是钉钉登录回调
    if (window.location.href.includes('code')) {
      const code = window.location.href.split('?')[1].split('&')[0].split('=')[1];
      const error = window.location.href.split('?')[1].split('&')[1].split('=')[1];
      console.log(code, error);

      if (code) {
        // 有code参数，说明是钉钉登录回调
        this.handleDingTalkCallback(code);
      } else if (error) {
        // 登录失败
        this.openNotification("钉钉登录失败，请重试");
      }
    }
    else {
      console.log(storage.nowurl, window.location.url,"111111");
      if (storage.nowurl != window.location.href) {
        storage.nowurl = window.location.href;
        window.location.reload()
      }
    }


  }

  // 处理钉钉登录回调
  handleDingTalkCallback = (code) => {
    fetch("/admin/sys/checkDingTalkLogin", {
      method: 'POST',
      mode: 'cors',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ code })
    })
      .then(response => response.json())
      .then(data => {
        if (data.success) {
          // 存储用户信息
          storage.ygxm = data.data.xm;
          storage.js = data.data.js;
          storage.zh = data.data.zh;
          storage.ygbh = data.data.zh;
          storage.userid = data.data.id;
          storage.yhlx = data.data.yhlx;
          storage.gysbm = data.data.zh;
          storage.logintime = this.getCurrentDate(2);

          this.openNotification(`欢迎您，${data.data.xm}!`);
          this.props.history.push({ pathname: '/shipSRM/mainpage', state: {} });
        } else {
          this.openNotification(data.message || "登录失败，请重试");
        }
      })
      .catch(error => {
        console.error('钉钉登录失败:', error);
        this.openNotification("登录失败，请重试");
      });
  }

  // 钉钉扫码登录
  handleDingTalkLogin = () => {
    fetch("/admin/sys/getDingTalkLoginUrl", {
      method: 'POST',
      mode: 'cors',
      headers: {
        'Content-Type': 'application/json'
      }
    })
      .then(response => response.json())
      .then(data => {
        if (data.success) {
          // 直接跳转到钉钉登录页面
          window.location.href = data.data;
        } else {
          this.openNotification("获取钉钉登录二维码失败");
        }
      })
      .catch(error => {
        console.error('获取钉钉登录二维码失败:', error);
        this.openNotification("获取钉钉登录二维码失败");
      });
  }

  componentWillUnmount() {
    document.removeEventListener('keydown', this.handleKeyDown);
  }

  inputOnBlur = () => {
    window.scroll(0, 0);
  }

  render() {
    const options = this.state.corplistdata.map(d => <Option value={d.ID}>{d.CORPNAME}</Option>);
    const { ddLoginVisible, ddLoginUrl } = this.state;

    return (
      <div>
        <div style={{
          width: "100vw", height: "100vh", position: "absolute",
          fontSize: "2rem", textAlign: "center", color: "white", overflow: "hidden",
          background: "linear-gradient(135deg, #333 0%, #444 50%, #333 100%)",
          backgroundSize: "100% 100%",
          backgroundImage: "repeating-linear-gradient(45deg, rgba(255, 255, 255, 0.05) 0px, rgba(255, 255, 255, 0.05) 1px, transparent 1px, transparent 2px), linear-gradient(135deg, #333 0%, #444 50%, #333 100%)",
          boxShadow: "inset 0 0 100px rgba(255, 255, 255, 0.1)",
          borderTop: "1px solid rgba(255, 255, 255, 0.2)",
          borderLeft: "1px solid rgba(255, 255, 255, 0.2)",
          borderRight: "1px solid rgba(0, 0, 0, 0.2)",
          borderBottom: "1px solid rgba(0, 0, 0, 0.2)"
        }}>

          <div style={{ height: "3vh", position: "relative", left: "0", top: "8vh", backgroundColor: "" }} >

          </div>
          <div style={{
            whidth: "64vw", height: "64vh", position: "absolute", left: "18vw", right: "18vw", top: "18vh",
            backgroundSize: "100% 100%", borderRadius: "0.5rem", boxShadow: "0 0 40px rgba(0,0,0,0.7)",
            border: "2px solid #555", backgroundColor: "#303030", borderTop: "8px solid #E62129"
          }}>
            <div style={{ height: "51.2vh", width: "25.6vw", position: "absolute", right: "0.8vw", top: "3.2vw", textAlign: "center", fontSize: "0.8vw", color: "white" }}>
              <div style={{ height: "10%", width: "80%", position: "relative", top: "5%", left: "10%", margin: "0", padding: "0", display: "flex", color: "white", fontSize: "1.44vw", fontWeight: "bold", alignItems: "center", justifyContent: "center" }}>
                甬舟能源技术股份有限公司
              </div>
              <div style={{
                height: "10%", width: "80%", position: "relative", top: "10%", left: "10%", margin: "0", padding: "0", display: "flex",
                color: "#ffe6e6", fontSize: "1.12vw", fontWeight: "500", alignItems: "center", justifyContent: "center"
              }}>
                供应链管理系统
              </div>

              <div style={{ height: "5.5vh", width: "80%", position: "relative", top: "15%", left: "10%", margin: "0", padding: "0", display: "flex", color: "black", fontSize: "0.96vw", fontWeight: "bold", alignItems: "center", justifyContent: "center" }}>
                <div style={{ height: "100%", width: "6.5vh", backgroundImage: `url(${userpic}) `, backgroundSize: "100% 100%", position: "absolute", top: "0", left: "0", backgroundColor: "#333", borderTopLeftRadius: "0.3rem", borderBottomLeftRadius: "0.3rem", borderLeft: "4px solid #E62129" }}>

                </div>
                <div style={{ height: "100%", width: "82%", position: "absolute", top: "0", right: "0", backgroundColor: "#444", borderTopRightRadius: "0.3rem", borderBottomRightRadius: "0.3rem" }}>
                  <Input placeholder="请输入用户名" style={{ width: "100%", height: "100%", border: "none", backgroundColor: "transparent", fontSize: "1.12vw", color: "#eee", textIndent: "2rem" }} onChange={e => this.handlechange_normal("username", e)} />
                </div>
              </div>
              <div style={{ height: "5.5vh", width: "80%", position: "relative", top: "15%", left: "10%", marginTop: "10%", padding: "0", display: "flex", color: "black", fontSize: "1.12vw", fontWeight: "bold", alignItems: "center", justifyContent: "center" }}>
                <div style={{ height: "100%", width: "6.5vh", backgroundImage: `url(${passwordpic}) `, backgroundSize: "100% 100%", position: "absolute", top: "0", left: "0", backgroundColor: "#333", borderTopLeftRadius: "0.3rem", borderBottomLeftRadius: "0.3rem", borderLeft: "4px solid #E62129" }}>

                </div>

                <div style={{ height: "100%", width: "82%", position: "absolute", top: "0", right: "0", backgroundColor: "#444", borderTopRightRadius: "0.3rem", borderBottomRightRadius: "0.3rem" }}>
                  <Input type="password" placeholder="请输入密码"
                    style={{ width: "100%", height: "100%", border: "none", backgroundColor: "transparent", fontSize: "1.12vw", color: "#eee", textIndent: "2rem" }}
                    onChange={e => this.handlechange_normal("password", e)} />
                </div>
              </div>
              <div style={{ height: "10%", width: "80%", position: "relative", top: "15%", left: "10%", marginTop: "10%", padding: "0", display: "flex", color: "black", fontSize: "0.96rem", fontWeight: "bold", alignItems: "center", justifyContent: "center" }}>
                <Button type="primary" onClick={this.handlelogin}
                  style={{
                    position: "relative", height: "2.24vw", fontSize: "1.12vw", width: "100%", left: "0", borderRadius: "0.3rem", backgroundColor: "#E62129", border: "none",
                    right: "0", margin: "auto", color: "#eeeeee"
                  }}
                  large><strong>登录</strong></Button>
              </div>
              {/* <div style={{ height: "10%", width: "80%", position: "relative", top: "15%", left: "10%", marginTop: "2%", padding: "0", display: "flex", color: "black", fontSize: "0.96rem", fontWeight: "bold", alignItems: "center", justifyContent: "center" }}>
                <Button type="primary" onClick={() => this.handleDingTalkLogin()}
                  style={{
                    position: "relative", height: "2.24vw", fontSize: "1.12vw", width: "100%", left: "0", borderRadius: "0.3rem", backgroundColor: "#1AAD19", border: "none",
                    right: "0", margin: "auto", color: "#eeeeee"
                  }}
                  large><strong>钉钉扫码登录</strong></Button>
              </div> */}
              <div style={{height:"10%",width:"80%",position:"relative",top:"15%",left:"10%",marginTop:"10%",padding:"0",display:"flex",color:"black",fontSize:"1rem",alignItems:"center",justifyContent:"space-between"}}>

                          <Resetpassword username={this.state.formdata.username}/>
                          <Registaccount/>
                      </div>


            </div>

            <div style={{ position: "absolute", left: "1.6vw", top: "3.2vw", width: "32vw", height: "51.2vh", display: "flex", flexDirection: "column", justifyContent: "center", alignItems: "center" }}>
              {/* <div style={{
                width: "240px", 
                height: "80px", 
                display: "flex", 
                justifyContent: "center", 
                alignItems: "center",
                marginBottom: "8px"
              }}>
                <img 
                  src={shiplogo} 
                  alt="Julong Logo" 
                  style={{
                    width: "40%", 
                    height: "auto", 
                    filter: "drop-shadow(0 0 10px #E62129)",
                    maxWidth: "200px"
                  }} 
                />
              </div> */}

              <svg xmlns="http://www.w3.org/2000/svg" height="240" width="240" style={{ marginTop: "1.6vh" }}>
                <g style={{ order: -1 }}>
                  <polygon
                    transform="rotate(45 120 120)"
                    strokeWidth="1.5"
                    stroke="#E62129"
                    fill="none"
                    points="84,84 177.6,60 156,156 60,180"
                    id="bounce1"
                  />
                  <polygon
                    transform="rotate(45 120 120)"
                    strokeWidth="1.5"
                    stroke="#E62129"
                    fill="none"
                    points="84,84 177.6,60 156,156 60,180"
                    id="bounce2"
                  />
                  <polygon
                    transform="rotate(45 120 120)"
                    strokeWidth="3"
                    stroke=""
                    fill="#414141"
                    points="84,84 180,60 156,156 60,180"
                  />
                  <polygon
                    strokeWidth="3"
                    stroke=""
                    fill="url(#gradiente)"
                    points="120,84 180,120 120,156 60,120"
                  />
                  <defs>
                    <linearGradient y2="100%" x2="10%" y1="0%" x1="0%" id="gradiente">
                      <stop style={{ stopColor: "#1e2026", stopOpacity: 1 }} offset="20%" />
                      <stop style={{ stopColor: "#414750", stopOpacity: 1 }} offset="60%" />
                    </linearGradient>
                  </defs>
                  <polygon
                    transform="translate(24, 37.2)"
                    strokeWidth="3"
                    stroke=""
                    fill="#E62129"
                    points="96,60 96,90 96,118.8 48,90"
                  />
                  <polygon
                    transform="translate(24, 37.2)"
                    strokeWidth="3"
                    stroke=""
                    fill="url(#gradiente2)"
                    points="48,-48 96,-48 96,118.8 48,90"
                  />
                  <defs>
                    <linearGradient y2="100%" x2="0%" y1="-17%" x1="10%" id="gradiente2">
                      <stop style={{ stopColor: "#d3a51000", stopOpacity: 1 }} offset="20%" />
                      <stop
                        style={{ stopColor: "#c01d0054", stopOpacity: 1 }}
                        offset="100%"
                        id="animatedStop1"
                      />
                    </linearGradient>
                  </defs>
                  <polygon
                    transform="rotate(180 120 120) translate(24, 24)"
                    strokeWidth="3"
                    stroke=""
                    fill="#E62129"
                    points="96,60 96,90 96,118.8 48,90"
                  />
                  <polygon
                    transform="rotate(0 120 120) translate(72, 24)"
                    strokeWidth="3"
                    stroke=""
                    fill="url(#gradiente3)"
                    points="48,-48 96,-48 96,102 48,132.24"
                  />
                  <defs>
                    <linearGradient y2="100%" x2="10%" y1="0%" x1="0%" id="gradiente3">
                      <stop style={{ stopColor: "#d3a51000", stopOpacity: 1 }} offset="20%" />
                      <stop
                        style={{ stopColor: "#c71e0054", stopOpacity: 1 }}
                        offset="100%"
                        id="animatedStop2"
                      />
                    </linearGradient>
                  </defs>
                  <polygon
                    transform="rotate(45 120 120) translate(96, 114)"
                    strokeWidth="3"
                    stroke=""
                    fill="#e4725d"
                    points="6,0 6,6 0,6 0,0"
                    id="particles1"
                  />
                  <polygon
                    transform="rotate(45 120 120) translate(96, 66)"
                    strokeWidth="3"
                    stroke=""
                    fill="#E62129"
                    points="7.2,0 7.2,7.2 0,7.2 0,0"
                    id="particles2"
                  />
                  <polygon
                    transform="rotate(45 120 120) translate(84, 96)"
                    strokeWidth="3"
                    stroke=""
                    fill="#fff"
                    points="2.4,0 2.4,2.4 0,2.4 0,0"
                    id="particles3"
                  />
                  <polygon
                    strokeWidth="3"
                    stroke=""
                    fill="#292d34"
                    points="35.4,119.76 120,170.4 120,206.4 35.4,156"
                  />
                  <polygon
                    transform="translate(60, 110.4)"
                    strokeWidth="3"
                    stroke=""
                    fill="#1f2127"
                    points="60,60 144.6,9.6 144.6,42 60,96"
                  />
                </g>
              </svg>


            </div>
          </div>




        </div>




        {/*    <Input onBlur={this.inputOnBlur} style={{backgroundColor:"white",position:"relative",
    width:"72%",left:"0",right:"0",margin:"0",height:"2rem"}}  value={this.state.deviceno}
    placeholder="扫描或者输入工位编号" onChange={event=>this.handledeviceno(event)}/>*/}









      </div>


    )
  }
}

export default Login
//styles
var styles = {
  containertyle: {
    height: "92vh", width: "100%", position: "absolute",
    left: "0", right: "0", margin: "auto",
    top: "0", backgroundImage: "linear-gradient(to bottom right, #00AAEB , #A28CB9)"
  }

}






